<template>
  <a-spin :spinning="loading" class="page-miH page-bgBack">
    <div class="body">
      <a-tabs v-model="tabsKey" @change="callback">
        <a-tab-pane key="1" tab="本地数据校验">
          <div>
            <div style="display: flex; justify-content: space-between">
              <a-month-picker :allowClear="false" placeholder="选择月份" v-model="dynamicDate" @change="onMonthChange" />
              <a-button type="primary" @click="download">下载模板</a-button>
            </div>
            <div v-if="infoList.length > 0">
              <div class="fix-item-wrapper" v-for="(item, index) in infoList" :key="index">
                <div class="fix-item-one" style="display: flex; flex-direction: column">
                  <div class="fix-item-name" style="margin-bottom: 0">
                    {{ item.year + "年" + item.month + "月" }}
                  </div>
                </div>
                <div class="fix-item-two">
                  <div>
                    <div class="childpProjectName">参保人数</div>
                    <div class="childContentName">{{ item.empCount }}人</div>
                  </div>
                </div>
                <div class="fix-item-two">
                  <div>
                    <div class="childpProjectName">社保缴费</div>
                    <div class="childContentName">{{ item.socAmount }}元</div>
                  </div>
                </div>
                <div class="fix-item-two">
                  <div>
                    <div class="childpProjectName">公积金缴费</div>
                    <div class="childContentName">{{ item.pfAmount }}元</div>
                  </div>
                </div>
                <div class="fix-item-two">
                  <div>
                    <div class="childpProjectName">校验文件</div>
                    <div style="display: flex; padding-right: 12px; width: 160px">
                      <div class="childContentName">
                        <a-upload
                          ref="upload"
                          :file-list="fileList"
                          :remove="handleRemove"
                          action="/file/api/v1/general/upload/inline"
                          :before-upload="beforeUpload"
                          accept=".xls, .xlsx"
                        >
                          <a-button v-if="fileList.length === 0" style="padding: 0" type="link" block>
                            <a-icon type="plus" />上传文件
                          </a-button>
                        </a-upload>
                      </div>
                      <a-upload
                        ref="upload"
                        :file-list="fileList"
                        :remove="handleRemove"
                        action="/file/api/v1/general/upload/inline"
                        :before-upload="beforeUpload"
                        accept=".xls, .xlsx"
                      >
                        <a-button type="link" v-if="fileList.length > 0">重传</a-button>
                      </a-upload>
                    </div>
                  </div>
                </div>
                <div class="fix-item-four">
                  <div>
                    <a-button type="link" :disabled="fileList.length === 0 || errData === true" block @click="parseImport(item)"
                      >数据校验</a-button
                    >
                  </div>
                  <div>
                    <a-button :disabled="item.checkCount === 0" type="link" block @click="goDetail(item, 1)">查看结果</a-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else style="margin-top: 80px">
              <a-empty />
            </div>

            <a-modal :width="600" title="本地数据预览" :visible="nextVisible" :footer="null" @cancel="nextVisible = false">
              <a-alert v-if="errData" message="上传表数据有误，不可进行数据校验。请检查" type="warning" show-icon />
              <a-table style="margin-top: 12px" :pagination="false" :scroll="{ x: 600 }" :columns="columns" :data-source="dataList">
                <template slot="parseResult" slot-scope="text, record">{{
                  text === null ? "成功" : "失败：（原因）" + record.parseRemark
                }}</template>
              </a-table>
            </a-modal>
            <a-modal
              title="数据校验"
              :visible="checkingVisible"
              :ok-button-props="{ style: { display: 'none' } }"
              cancel-text="取消校验"
              @cancel="deleteCheck"
            >
              <div style="font-size: 16px; font-weight: 500; color: #000000; display: flex; justify-content: center; align-items: center">
                <img style="width:width: 57px;height:66px;margin-right:12px" :src="checkingImg" />正在进行数据校验，请稍后...
              </div>
            </a-modal>
          </div>
        </a-tab-pane>
        <!-- <a-tab-pane key="2" tab="官方数据校验">
          <div>
            <div style="display: flex; justify-content: space-between">
              <a-month-picker :allowClear="false" placeholder="选择月份" v-model="dynamicDate" @change="onMonthChange" />
            </div>
            <div v-if="officialInfoList.length > 0">
              <div class="fix-item-wrapper" v-for="(item, index) in officialInfoList" :key="index">
                <div class="fix-item-one" style="display: flex; flex-direction: column">
                  <div class="fix-item-name" style="margin-bottom: 0">
                    {{ item.year + "年" + item.month + "月" }}
                  </div>
                </div>
                <div class="fix-item-three">
                  <div>
                    <div class="childpProjectName">参保人数</div>
                    <div class="childContentName">{{ item.empCount }}人</div>
                  </div>
                </div>
                <div class="fix-item-three">
                  <div>
                    <div class="childpProjectName">社保缴费</div>
                    <div class="childContentName">{{ item.socAmount }}元</div>
                  </div>
                </div>
                <div class="fix-item-three">
                  <div>
                    <div class="childpProjectName">公积金缴费</div>
                    <div class="childContentName">{{ item.pfAmount }}元</div>
                  </div>
                </div>

                <div class="fix-item-four">
                  <div>
                    <a-button type="link" block @click="showCheck(item)">数据校验</a-button>
                  </div>
                  <div>
                    <a-button type="link" block @click="goDetail(item, 2)">查看结果</a-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else style="margin-top: 80px">
              <a-empty />
            </div>
            <a-modal :visible="checkVisible" title="数据校验" okText="开始校验" @ok="handleOk" @cancel="handleCancel">
              <div style="display: flex; justify-content: center; align-items: center">
                <a-label> <span style="color: #fa5051">*</span>选择城市： </a-label>
                <a-select style="width: 300px" allowClear v-model="city" @change="handleSelectChange" placeholder="请选择城市">
                  <a-select-option v-for="item in progNameList" :key="item.areaId">{{ item.areaName }}</a-select-option>
                </a-select>
              </div>
              <div style="display: flex; justify-content: center; align-items: center; margin-top: 12px">
                <div class="typebox" v-for="(item, index) in typeList" :key="index">
                  <div class="typeBoxItem">
                    <xq-icon
                      :class="item.accountType === '公积金' ? 'gjj' : item.accountType === '医保' ? 'yb' : 'sb'"
                      type="icon-shuju33x"
                    ></xq-icon>
                    <div style="color: #55565d; font-size: 12px; margin-left: 8px">
                      {{ item.accountType ? item.accountType : "--" }}数据校验
                    </div>
                  </div>
                  <div class="typeBoxItem" style="margin-top: 16px">
                    <div class="boxContentName">账号名称：</div>
                    <div
                      style="color: #55565d; font-size: 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 70px"
                    >
                      {{ item.accountName ? item.accountName : "--" }}
                    </div>
                  </div>
                  <div class="typeBoxItem" style="margin-top: 6px">
                    <div class="boxContentName">登陆状态：</div>
                    <div
                      :style="[
                        { color: item.isLogin ? '#6A66F6' : '#55565D' },
                        { fontSize: '10px' },
                        { marginLeft: '12px' },
                        { cursor: !item.isLogin ? 'pointer' : '' }
                      ]"
                      @click="!item.isLogin ? Login(item.loginUrl) : null"
                    >
                      {{ item.isLogin ? "已登录" : "未登录" }}
                    </div>
                  </div>
                  <div class="typeBoxItem" style="margin-top: 6px">
                    <div class="boxContentName">是否校验：</div>
                    <div>
                      <a-switch :disabled="!item.isLogin" v-model="item.isSwitch" @change="swichChange(item)" />
                    </div>
                  </div>
                </div>
              </div>
              <div class="prompt">
                <div style="font-size: 14px; font-weight: bold; color: #3c3d43">温馨提示</div>
                <div class="gray" style="font-size: 12px; line-height: 21px; margin-top: 8px">
                  同步数据需开启
                  <span class="edit" style="font-size: 12px; cursor: pointer" @click="downloadDSJ"> 大数据助手 </span>
                  插件，并登录相应网站才可使用
                </div>
              </div>
            </a-modal>
            <a-modal
              title="数据校验"
              :visible="checkingVisible"
              :ok-button-props="{ style: { display: 'none' } }"
              cancel-text="取消校验"
              @cancel="deleteCheck"
            >
              <div style="font-size: 16px; font-weight: 500; color: #000000; display: flex; justify-content: center; align-items: center">
                <img style="width:width: 57px;height:66px;margin-right:12px" :src="checkingImg" />正在进行数据校验，请稍后...
              </div>
            </a-modal>
          </div>
        </a-tab-pane> -->
      </a-tabs>
    </div>
  </a-spin>
</template>

<script>
import { getGinseng, saveImport, getCity, getCityAcc, socChecks } from "./api";
import UploadMixin from "xqjr-plugin-common/UploadOrExport/uploadMixin";
const mixin = new UploadMixin();
import axios from "axios";
import moment from "moment";
const columns = [
  { title: "姓名", width: 120, dataIndex: "name", key: "name", fixed: "left" },
  { title: "身份证号", dataIndex: "idCard", key: "idCard", width: 200 },
  { title: "参保月份", dataIndex: "belongsDate", key: "belongsDate", width: 150 },
  { title: "缴费类型", dataIndex: "payCostType", key: "payCostType", width: 120 },
  { title: "个人社保费", dataIndex: "personalSocAmount", key: "personalSocAmount", width: 120 },
  { title: "单位社保费", dataIndex: "companySocAmount", key: "companySocAmount", width: 120 },
  { title: "个人公积金费", dataIndex: "personalPfAmount", key: "personalPfAmount", width: 120 },
  { title: "单位公积金费", dataIndex: "companyPfAmount", key: "companyPfAmount", width: 120 },
  { title: "服务费", dataIndex: "serviceCost", key: "serviceCost", width: 120 },
  { title: "滞纳金", dataIndex: "lateFees", key: "lateFees", width: 120 },
  {
    title: "检测结果",
    dataIndex: "parseResult",
    key: "parseResult",
    width: 220,
    scopedSlots: { customRender: "parseResult" },
    fixed: "right"
  }
];
export default {
  mixins: [mixin],
  data() {
    return {
      columns,
      city: undefined,
      yibaoSycnData: [],
      needSyncDate: [
        { areId: 283, needSyncType: ["医保"] } // 青岛医保
      ],
      typeList: [],
      cityDetail: {},
      loading: false,
      isContinue: false,
      formData: {},
      urlList: [],
      errData: false,
      infoList: [],
      progNameList: [],
      officialInfoList: [],
      gjsSwich: "",
      sbSwich: "",
      ybSwich: "",
      dataList: [],
      itemDetail: {},
      fileName: "",
      fileList: [],
      nextVisible: false,
      defaultFangan: null,
      tabsKey: this.$route.query.index ? this.$route.query.index : "1",
      params: {
        templateName: "socCheckImportTemplate.xlsx"
      },
      url: `/salary/api/v1/excel/template/download`,
      excelName: "数据校验上传模板.xlsx",
      dynamicDate: moment(moment().format("YYYY-MM"), "YYYY-MM"),
      companyId: this.$store.state.hr.companyId,
      checkVisible: false,
      checkingVisible: false,
      checkingImg: require("@/assets/img/checking.png")
    };
  },
  created() {
    this.getGinsengList();
    this.action = `/hr/api/v1/socChecks/parseImport`;
    var that = this;
    // 监听来自插件的同步数据
    document.addEventListener("SynDataButton", function (e) {
      that.spinning = false;
      switch (e.detail.from) {
        case "青岛医保":
          var count = e.detail.arry.length;
          for (var i = 0; i < count; i++) {
            that.yibaoSycnData.push(e.detail.arry[i]);
          }
          break;
      }
    });
  },
  methods: {
    swichChange(e) {
      if (e === true) {
        // 检查该地区医保是否需要前端进行同步数据
        if (this.yibaoSwitch === true) {
          // 检查该地区医保是否需要前端进行同步数据
          let isSync = false;
          for (var i = 0; i < this.needSyncDate.length; i++) {
            if (this.needSyncDate[i].areId === this.defaultFangan) {
              // 确认地区
              for (var j = 0; j < this.needSyncDate[i].needSyncType.length; j++) {
                if (this.needSyncDate[i].needSyncType[j] === "医保") {
                  isSync = true;
                  break;
                }
              }
              break;
            }
          }
          if (isSync) {
            // 需要同步
            switch (this.defaultFangan) {
              case 283: // 青岛地区
                this.spinning = true;
                window.postMessage(
                  {
                    start: this.syncDate[0],
                    end: this.syncDate[1],
                    cookie: this.yibaoLogin.cookie,
                    type: "青岛医保" // 这个值会原封不动的传递回来
                  },
                  "*"
                );
                break;
            }
          }
        }
      } else {
        this.yibaoSycnData = [];
      }
      this.isContinue = false;
      this.typeList.forEach((item, index) => {
        if (item.isSwitch && item.isSwitch === true) {
          this.isContinue = true;
        }
      });
    },
    Login(e) {
      if (e) {
        window.open(e);
      }
    },
    downloadDSJ() {
      window.open("https://www.yuque.com/docs/share/aadc62e4-0ea4-4387-80f3-ad8cd724018f?#");
    },
    parseImport(e) {
      axios({
        url: `/hr/api/v1/socChecks/saveImport?socMonthId=${e.id}&year=${e.year}&month=${e.month}&checkType=1&companyId=${this.companyId}&fileUrl=${this.urlList[0]}&fileName=${this.fileName}`,
        method: "post",
        data: this.formData,
        headers: this.headers
      })
        .then((res) => {
          this.$message.success("校验成功");
          this.getGinsengList();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getGinsengList() {
      this.loading = true;
      getGinseng({
        companyId: this.companyId,
        checkType: 1,
        month: moment(this.dynamicDate).format("MM"),
        year: moment(this.dynamicDate).format("YYYY")
      })
        .then((res) => {
          this.infoList = JSON.parse(JSON.stringify(res.data));
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
      getGinseng({
        companyId: this.companyId,
        checkType: 2,
        month: moment(this.dynamicDate).format("MM"),
        year: moment(this.dynamicDate).format("YYYY")
      })
        .then((res) => {
          this.officialInfoList = JSON.parse(JSON.stringify(res.data));
        })
        .catch((err) => {
          console.log(err);
        });
    },
    beforeUpload(file) {
      this.fileList = [file];
      if (this.fileList && this.fileList.length > 0) {
        this.fileName = this.fileList[0].name;
        const { fileList } = this;
        this.formData = new FormData();
        const formData2 = new FormData();
        fileList.forEach((file) => {
          this.formData.append("file", file);
        });
        fileList.forEach((file) => {
          formData2.append("files", file);
        });
        // this.uploading = true;
        axios({
          url: this.action,
          method: "post",
          data: this.formData,
          headers: this.headers
        }).then((res) => {
          // this.reset();
          axios({
            url: "/file/api/v1/general/upload/inline",
            method: "post",
            data: formData2,
            headers: this.headers
          }).then((res) => {
            this.urlList = res.data.data;
          });
          // this.handleSuccess(res.data);
          // this.uploading = false;
          this.nextOk(res.data);
        });
      } else {
        this.reset();
        this.handleUploadError();
      }
      return false;
    },
    // 校验上传文件后弹出本地数据预览列表
    nextOk(e) {
      this.errData = false;
      this.dataList = e.data;
      this.nextVisible = true;
      this.dataList.forEach((item) => {
        if (item.parseResult === false) {
          this.errData = true;
        }
      });
    },
    // 取消校验
    deleteCheck() {
      this.checkingVisible = false;
    },
    // 查看结果
    goDetail(e, state) {
      console.log(e);
      this.$router.push({
        path: "./detail", // 员工异动
        query: { id: e.id, month: e.month, year: e.year, state: state }
      });
    },
    callback(index) {
      const query = JSON.parse(JSON.stringify(this.$router.history.current.query)); // 取当前路由query值并且深拷贝
      const path = this.$router.history.current.path; // 取当前路由地址
      query.index = index; // 修改变动的query值
      this.$router.push({ path, query }); // 改变query值
    },
    // 月份选择变化
    onMonthChange(e) {
      console.log(e);
      this.getGinsengList();
    },
    showCheck(e) {
      this.city = undefined;
      this.typeList = [];
      this.itemDetail = e;
      getCity({ isDistinct: true })
        .then((res) => {
          this.progNameList = [];
          if (res.data) {
            this.progNameList = res.data;
          }
        })
        .catch((err) => {
          this.$message.error("失败!");
          console.log("debug log --> ", err);
        });
      this.checkVisible = true;
      this.isContinue = false;

      // this.checkingVisible = true;
    },
    // 点击校验确定按钮
    handleOk(e) {
      this.gjsSwich = "";
      this.sbSwich = "";
      this.ybSwich = "";
      this.typeList.forEach((item, index) => {
        if (!item.isSwitch) {
          item.isSwitch = false;
        }
        if (item.accountType === "公积金") {
          this.gjsSwich = item.isSwitch;
        } else if (item.accountType === "社保") {
          this.sbSwich = item.isSwitch;
        } else if (item.accountType === "医保") {
          this.ybSwich = item.isSwitch;
        }
      });
      console.log(this.typeList);
      // setTimeout(() => {
      //   this.checkVisible = false;
      //   this.checkingVisible = true;
      // }, 500);
      if (!this.city) {
        this.$message.error("请选择校验城市");
      } else if (!this.isContinue) {
        this.$message.error("请选择校验类型");
      } else {
        socChecks({
          month: moment(this.dynamicDate).format("MM"),
          year: moment(this.dynamicDate).format("YYYY"),
          companyId: this.companyId,
          monthId: this.itemDetail.id,
          checkType: 2,
          areaId: this.cityDetail.areaId,
          syncServiceBeanName: this.cityDetail.syncServiceBeanName,
          socInfo: [],
          meInfo: this.yibaoSycnData,
          pfInfo: [],
          socIsTrue: this.sbSwich,
          pfIsTrue: this.gjsSwich,
          meIsTrue: this.ybSwich
        })
          .then((res) => {
            this.$message.success("校验成功");
            this.getGinsengList();
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    handleCancel(e) {
      this.checkVisible = false;
    },
    // 选择城市
    handleSelectChange(e) {
      console.log(e);
      this.defaultFangan = e;
      this.progNameList.forEach((item, index) => {
        if (item.areaId === e) {
          this.cityDetail = item;
        }
      });

      getCityAcc({ areaId: e })
        .then((res) => {
          this.typeList = res.data;
        })
        .catch((err) => {
          this.$message.error("失败!");
          console.log("debug log --> ", err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.gjj {
  color: #6b6bf2;
}
.yb {
  color: #32ccaa;
}
.sb {
  color: #4686ff;
}
.prompt {
  margin-top: 12px;
  padding: 15px;
  width: 100%;
  height: 80px;
  background: #faf9f9;
  border-radius: 4px;
  .edit {
    color: var(--primary);
  }
}
.typeBoxItem {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.typebox {
  padding: 12px;
  margin: 10px;
  width: 148px;
  height: 127px;
  background: #fafafa;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}
.body {
  padding: 24px;
}
.boxContentName {
  color: #767885;
  font-size: 10px;
  width: 70px;
}
.fix-item-wrapper {
  display: flex;
  width: 100%;
  height: 110px;
  background: #ffffff;
  border-radius: 8px;
  margin-bottom: 20px;
  margin-top: 25px;
  padding: 20px;
  border: 1px solid #e8e8e8;
  display: flex;
  .ant-btn {
    height: 0;
    padding: 0px 4px;
  }
  .fix-item-one {
    margin-top: 10px;
    height: 40px;
    display: flex;
    align-self: center;
    padding-left: 40px;
    width: 15%;
    border-right: 1px solid #e8e8e8;
  }

  .fix-item-two {
    padding-left: 45px;
    margin-top: 16px;
    width: 17%;
    height: 45px;
    padding-right: 40px;
    border-right: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .fix-item-three {
    padding-left: 45px;
    margin-top: 16px;
    width: 21%;
    height: 45px;
    padding-right: 40px;
    border-right: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .fix-item-four {
    width: 20%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 40px;
    padding-right: 40px;
  }
  .fix-item-name {
    font-size: 18px;
    font-weight: 500;
    color: #3c3d43;
    line-height: 28px;
  }
  .childpProjectName {
    font-size: 14px;
    font-weight: 400;
    color: #767885;
    padding-bottom: 12px;
  }
  .childContentName {
    height: 35px;
    width: 130px;
    padding-bottom: 12px;
    font-size: 20px;
    font-weight: 500;
    color: #55565d;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
